import warnings
warnings.filterwarnings('ignore')
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(40)
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.models import Sequential,Model
from tensorflow.keras.layers import Conv2D,MaxPool2D,Flatten,Dense,BatchNormalization,ReLU,Input
from tensorflow.keras.losses import categorical_crossentropy
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical

(x_train,y_train),(x_test,y_test) = cifar10.load_data()

x_train = x_train/255
x_test = x_test/255
y_train = to_categorical(y_train,10)
y_test = to_categorical(y_test,10)

train = tf.data.Dataset.from_tensor_slices((x_train,y_train)).shuffle(1000).batch(128)
test = tf.data.Dataset.from_tensor_slices((x_test,y_test)).shuffle(1000).batch(128)

def Conv(x,ch):
    x = Conv2D(ch,(3,3),padding='same')(x)
    x = BatchNormalization()(x)
    x = ReLU()(x)
    return x

inputs = Input((32,32,3))

x = Conv(inputs,64)
x = Conv(x,64)
x = MaxPool2D()(x)

x = Conv(x,128)
x = Conv(x,128)
x = MaxPool2D()(x)

x = Conv(x,256)
x = Conv(x,256)
x = Conv(x,256)
x = MaxPool2D()(x)

x = Conv(x,512)
x = Conv(x,512)
x = Conv(x,512)
x = MaxPool2D()(x)

x = Conv(x,512)
x = Conv(x,512)
x = Conv(x,512)
x = MaxPool2D()(x)

x = Flatten()(x)
x = Dense(256,activation='relu')(x)
x = Dense(64,activation='relu')(x)
outputs = Dense(10,activation='softmax')(x)

model = Model(inputs,outputs)
model.summary()

model.compile(optimizer='adam',loss=categorical_crossentropy,metrics=['accuracy'])
model.fit(train,epochs=3,validation_data=test)
score = model.evaluate(test,verbose=0)
print('损失值:',score[0])
print('准确率:',score[1])
